/*
 * Ganesa Copyright (C) 2008 Wim Crols <twimpiex@gnx.be>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package be.gnx.ganesa.application.controller;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import be.gnx.ganesa.application.ui.Ganesa;

public class Exit implements Listener, SelectionListener {

  private Ganesa ganesa;

  public Exit(Ganesa ganesa) {
    this.ganesa = ganesa;
  }

  public void handleEvent(Event event) {
    exit(null, event);
  }

  public void widgetDefaultSelected(SelectionEvent selectionEvent) {
    Exit.this.widgetSelected(selectionEvent);
  }

  public void widgetSelected(SelectionEvent selectionEvent) {
    exit(selectionEvent, null);
  }

  public void exit(SelectionEvent selectionEvent, Event event) {
    Display display = null;
    if (selectionEvent != null) {
      display = selectionEvent.display;
    } else if (event != null) {
      display = event.display;
    } else {
      return;
    }

    if ((ganesa.getApplication().getSelectedProject() == null) || (ganesa.getApplication().getSelectedProject().isSaved())) {
      if (selectionEvent != null) {
        for (Shell shell : display.getShells()) {
          shell.close();
        }
      }
    } else {
      if (display.getActiveShell() != null) {
        MessageBox messageBox = new MessageBox(display.getActiveShell(), SWT.APPLICATION_MODAL | SWT.YES | SWT.NO);
        messageBox.setText("Project is not saved!");
        messageBox.setMessage("The project is not saved!\nAre you sure you want to exit?");

        if (messageBox.open() == SWT.YES) {
          if (selectionEvent != null) {
            for (Shell shell : display.getShells()) {
              shell.close();
            }
          }
        } else {
          if (event != null) {
            event.doit = false;
          }
        }
      }
    }
  }

}
